package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.common.result.R;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.module.admin.entity.*;
import com.mars.module.admin.mapper.*;
import com.mars.module.admin.request.NewsRequest;
import com.mars.module.admin.service.INewsService;
import com.mars.module.system.entity.SysUser;
import com.mars.module.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 新闻业务层处理
 *
 * @author mars
 * @date 2024-03-04
 */
@Slf4j
@Service
@AllArgsConstructor
public class NewsServiceImpl implements INewsService {

    private final NewsMapper baseMapper;
    private final NewsCategoryMapper categoryMapper;
    private final SysUserMapper userMapper;
    private static String classId = "";


    @Override
    @Transactional(rollbackFor = Exception.class)
    public News add(NewsRequest request) {
        News entity = News.builder().build();
        BeanUtils.copyProperties(request, entity);
        if (request.getCategoryId() != null) {
            String[] split = request.getCategoryId().split(",");
            entity.setCategoryId(split[split.length - 1]);
        }
        entity.setLikes(0);
        entity.setViews(0);
        entity.setCollect(0);
        entity.setStatus("0");
        entity.setCreateById(ContextUserInfoThreadHolder.get().getId());
        entity.setCreateTime(LocalDateTime.now());
        baseMapper.insert(entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(NewsRequest request) {
        News entity = News.builder().build();
        BeanUtils.copyProperties(request, entity);
        if (request.getCategoryId() != null) {
            String[] split = request.getCategoryId().split(",");
            entity.setCategoryId(split[split.length - 1]);
        }
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public News getById(Long id) {
        News news = baseMapper.selectById(id);
        Long userId = ContextUserInfoThreadHolder.get().getId();
        String classId = getClassId(Long.valueOf(news.getCategoryId()));
        if (StringUtils.isBlank(classId)) {
            classId = news.getCategoryId().toString();
        }
        news.setCategoryId(classId);
        return news;
    }

    public String getClassId(Long id) {
        NewsCategory productClass = categoryMapper.selectById(id);
        if (productClass.getParentId() != 0L) {
            classId = productClass.getParentId().toString() + "," + productClass.getId();
            getClassId(productClass.getParentId());
        }
        return classId;
    }

    @Override
    public PageInfo<News> pageList(NewsRequest request) {
        Page<News> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<News> query = this.buildWrapper(request);
        IPage<News> pageRecord = baseMapper.selectPage(page, query);
        List<News> records = pageRecord.getRecords();
        List<News> recordsNew = new ArrayList<>();
        Long userId = ContextUserInfoThreadHolder.get().getId();
        for (News news : records) {
            NewsCategory category = categoryMapper.selectById(news.getCategoryId());
            news.setCategoryName(category == null ? "" : category.getCategoryName());
            if ("0".equals(news.getStatus())) {
                news.setStatus("未发布");
            } else if ("1".equals(news.getStatus())) {
                news.setStatus("已发布");
            }
            if (news.getContent().length() > 30) {
                news.setContent(news.getContent().substring(0, 70));
            }
            recordsNew.add(news);
        }
        pageRecord.setRecords(recordsNew);
        return PageInfo.build(pageRecord);
    }

    @Override
    public PageInfo<News> pageRecommendList() {
        String userId = ContextUserInfoThreadHolder.get().getId().toString();
        Page<News> page = new Page<>(1, 10);
        IPage<News> pageRecord = baseMapper.selectPage(page, new QueryWrapper<>());
        List<News> newsList = new ArrayList<>();
        Recommend recommend = new Recommend();
        //获取需要推荐的用户
        SysUser sysUser = userMapper.selectById(Long.valueOf(userId));
        List<NewsScore> recommendationNews = new ArrayList<>();
        if (sysUser != null) {
            recommendationNews = recommend.recommend(sysUser.getUserName(), getUserList());
            if (recommendationNews != null && !recommendationNews.isEmpty()) {
                System.out.println("-----------------------");
                System.out.println("推荐结果如下：");
                for (NewsScore newsScore : recommendationNews) {
                    System.out.println("新闻：" + newsScore.newsId + " ,评分：" + newsScore.score);
                }
                for (NewsScore score : recommendationNews) {
                    newsList.add(baseMapper.selectById(score.newsId));
                }
            }
        }
        pageRecord.setRecords(newsList);
        if (newsList.isEmpty()) {
            pageRecord.setTotal(0);
        } else {
            pageRecord.setTotal(newsList.size());
        }
        return PageInfo.build(pageRecord);
    }

    public List<User> getUserList() {
        List<User> resultList = new ArrayList<>();
        List<SysUser> userList = userMapper.selectList(new QueryWrapper<>());
        List<News> newsList = baseMapper.selectList(new QueryWrapper<News>().eq("status", "1"));
        for (SysUser sysUser : userList) {
            User user = new User();
            user.setUsername(sysUser.getUserName());
            for (News news : newsList) {
                int score = 0;
                if (score != 0) {
                    user.set(news.getTitle(), score, news.getId());
                }
            }
            resultList.add(user);
        }
        return resultList;
    }

    @Override
    public List<News> list(NewsRequest request) {
        LambdaQueryWrapper<News> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }


    private LambdaQueryWrapper<News> buildWrapper(NewsRequest param) {
        LambdaQueryWrapper<News> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getTitle())) {
            query.like(News::getTitle, param.getTitle());
        }
        if (StringUtils.isNotBlank(param.getContent())) {
            query.like(News::getContent, param.getContent());
        }
        if (StringUtils.isNotBlank(param.getAuthor())) {
            query.like(News::getAuthor, param.getAuthor());
        }
        if (param.getCategoryId() != null) {
            query.eq(News::getCategoryId, param.getCategoryId());
        }
        if (StringUtils.isNotBlank(param.getUrl())) {
            query.like(News::getUrl, param.getUrl());
        }
        if (StringUtils.isNotBlank(param.getStatus())) {
            query.eq(News::getStatus, param.getStatus());
        }
        return query;
    }

}
